package com.comp3111.happymeal;

import org.json.JSONException;
import org.json.JSONObject;

import com.configuration.Configuration;
import com.user.LoginRegister;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginTypeSmsActivity extends Activity {
	
	final int CORRECT = 1;
	final int WRONG   = 0;
	private int attemptAuthResult;
	public static LoginTypeSmsActivity instance;
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		instance = this;
		setContentView(R.layout.login_type_sms);
		 
		Bundle extras = getIntent().getExtras();
		final String telephone = extras.getString("TELEPHONE");
		
		// Set up the login form.
		final EditText et_login_type_sms_passcode = (EditText)findViewById(R.id.login_type_sms_passcode);
		Button btn_login_type_sms_next = (Button)findViewById(R.id.login_type_sms_next);
		
		//Configure the next button
		btn_login_type_sms_next.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
						
				final String passcode = et_login_type_sms_passcode.getText().toString();
						
				if(!checkPasscode(passcode)){
							
					if(Configuration.showLog){
						Log.d("LoginTypeSmsActivity","btn_login_type_sms_next");
					}
							
					wrongPasscodeAlert();
					return;
				}
						
				//Initialize attemptAuthResult
				attemptAuthResult = -1;
						
				//Start a new thread to attempt Login (requirement when connecting online)
				Thread attemptThread = new Thread(new Runnable(){  
					public void run(){  
						attemptAuthResult = attemptAuth(telephone,passcode);
					}
				});  
				attemptThread.start();
				
				while(attemptThread.isAlive()){
		        	//Waiting to get server response
		        }
		       
				if(attemptAuthResult == CORRECT){
					// Correct passcode entered
					// Jump to next intent
					Intent intentPass = new Intent(LoginTypeSmsActivity.this, LoginEditUserProfileActivity.class);
					
					//Pass pass intent								
					intentPass.putExtra("TELEPHONE",telephone.trim());
						
					//Go to next page
					startActivity(intentPass);
					finish();
				}else{
					//Wrong passcode entered
					Toast.makeText(LoginTypeSmsActivity.this,"Incorrect Passcode", Toast.LENGTH_LONG).show();
				}
			}
		});
	}
	 
	
	/*
	 * checkNumber checks whether the entered passcode is a 4 digit number
	 * Valid Definition
	 * 0000-9999
	 */
	private boolean checkPasscode(String passcode){
		int passcode_int = Integer.parseInt(passcode);
		
		if((passcode_int > 999 && passcode_int<10000)){
			return true;
		}else{
			return false;
		}
	}
	 
	 /*
	  * The app will not allow it to go back to LoginTypeSmsActivity through back
	  * Override the back button to prevent jumping back to LoadingScreenActivity
	  */
	public void onBackPressed(){
		if(Configuration.showLog){
			Log.d("LoginTypeSmsActivity", "onBackPressed");
		}
	}
	
	/*
	 * wrongPasscodeAlert prompt out a dialog asking for entering a valide passcode
	 */
	private void wrongPasscodeAlert(){
		AlertDialog.Builder dialog = new AlertDialog.Builder(LoginTypeSmsActivity.this);
		dialog.setTitle("Invalid Passcode");
		//dialog.setIcon(android.R.drawable.ic_dialog_alert);
		dialog.setMessage("Please enter a 4-digit passcode");
		dialog.setCancelable(false);
		dialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {  
		    public void onClick(DialogInterface dialog, int which) {  
		    	//Cancel Action
		    }  
		});
		dialog.show();
	}
	
	
	/*
	 * attemptLogin tries to login/register with the entered phone number
	 * It handles several messages returned by the server and return an integer
	 * Messages
	 * - WRONG 		: Wrong passcode entered
	 * - CORRECT	: Correct passcode entered
	 * 
	 * Return Values
	 * - 0 : WRONG
	 * - 1 : CORRECT
	 */
	private int attemptAuth(String telephone,String passcode){
		
		final String KEY_CORRECT	= "CORRECT";
		final String KEY_WRONG		= "WRONG";
		final String KEY_MESSAGE 	= "MESSAGE";
		
		LoginRegister loginRegister = new LoginRegister();
		JSONObject result = loginRegister.authUser(telephone,passcode,getApplicationContext());
		
		try {
			//Log.d("test","test");
			if(result.getString(KEY_MESSAGE)!= null){
				if(Configuration.showLog){
					Log.d("LoginTypeSmsActivity","KEY_MESSAGE = " + result.getString(KEY_MESSAGE));
				}
				if(result.getString(KEY_MESSAGE).equalsIgnoreCase(KEY_CORRECT)){
					return CORRECT;
				}else {
					return WRONG;
				}
			}else{
				if(Configuration.showLog){
					Log.d("LoginTypeSmsActivity Error","attemptAuth null reply");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("LoginTypeSmsActivity Error","attemptAuth Exception");
			}
		}
		
		return WRONG;
	}
	
}
